package wan.com.templateproject.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;

/**
 * @author wan
 * @version 1.0.0
 * @Description redis锁
 * @createTime 2021年10月15日 14:49:34
 */
public class RedisLock {

    @Autowired
    private static Jedis jedis;

    /**
     * 上锁
     * @param key
     * @param threadId
     */
    public static void getLock(String key, String threadId) {
        String value = threadId;
            t1:
            for (;;) {
                Long setnx = jedis.setnx(key, value);
                if (setnx == 1L) {
                    break t1;
                }else {
                    System.out.println("该线程正在等待》》》》》》》》》》》");
                }
            }
            System.out.println("当前线程名："+Thread.currentThread().getName());
        System.out.println("上锁成功");
    }

    /**
     * 解锁
     * @param key
     * @param threadId
     */
    public static void openLock(String key, String threadId) {
        if (threadId.equals(jedis.get(key))) {
            jedis.del(key);
        }
    }
}
